package tools

import (
	"fmt"
	RawCAN "github.com/linklayer/go-socketcan/pkg/socketcan"
	"time"
)

type defaultSerialization struct {
}

func (d *defaultSerialization) Serialize(frame *RawCAN.CanFrame) string {
	return serialize(frame)
}

func (d *defaultSerialization) Deserialize(a string) *replayFrame {
	return deserialize(a)
}

type Serialization interface {
	Serialize(*RawCAN.CanFrame) string
	Deserialize(string) *replayFrame
}

func serialize(f *RawCAN.CanFrame) string {
	return fmt.Sprintf("(%10.6f) Can%d %X#%s\n", float64(time.Now().UnixNano())/1000000000, f.ArbId>>12, f.ArbId&0xfff, bytes2string(f.Data))
}

func bytes2string(a []byte) string {
	return fmt.Sprintf("%X", a)
}

//
func deserialize(a string) *replayFrame {
	// TODO: to be tested
	var timeStamp float64
	var canInterface, canId uint32
	var data []byte

	_, err := fmt.Sscanf(a, "(%10.6f) Can%d %X#%X\n", &timeStamp, &canInterface, &canId, &data)
	if err != nil {
		fmt.Println("deserialize err: ", err)
	}

	return &replayFrame{
		timeStamp: int64(timeStamp * 1000000000),
		CanFrame: RawCAN.CanFrame{
			ArbId:    (canInterface << 12) | canId,
			Dlc:      byte(len(data)),
			Data:     data,
			Extended: false,
		},
	}
}
